'use strict';


const fs = require('fs');

const pump = require('mz-modules/pump');

const BaseController = require('./base.js');

class GoodsCateController extends BaseController {

    async index() {
        
        // 关联查询方法为 mongdb 原生查询方法  需要通过 mongoose 将字符串 _id 转化为 ObjectId
        let result = await this.ctx.model.GoodsCate.aggregate([
            {
                $lookup:{
                    from: 'goods_cate',          // 关联表 
                    localField: '_id',           // 本表 _id
                    foreignField: 'pid',         // 被关联表 对应的 id
                    as: 'items'
                }
            },
            {
                $match: {
                    "pid" : "0"
                }
            }
        ])

        await this.ctx.render('admin/goodsCate/index', {
            list: result
        })
    }

    async add() {

        let cateList = await this.ctx.model.GoodsCate.find({"pid": "0"});   // pid=0  表示顶级分类

        await this.ctx.render('admin/goodsCate/add', {
            cateList: cateList
        });
    }

    async doAdd() {

        // 获取上传的内容
        let parts = this.ctx.multipart({autoFields: true});
        let files = {};
        let stream;
        while ((stream = await parts()) != null ) {
            if (!stream.filename) {
                break;
            }
            let fieldname = stream.fieldname;   // file表单的名字

            let dir = await this.service.tools.getUploadFile(stream.filename);   // 返回上传路径地址与数据库保存地址
            let target = dir.uploadDir;
            let writeStream = fs.createWriteStream(target);

            await pump(stream, writeStream);  // 写入并销毁当前流  egg-demo方法

            files = Object.assign(files, {
                [fieldname]: dir.saveDir
            })

            // 上传图片成功以后  生成缩略图
            await this.service.tools.jimpImg(target);
        }

        // 如果分类 id 不等于 0  ，则不是顶级分类， 则需要将pid(字符串分类id) 转化为 ObjectId
        if (parts.field.pid != 0) {
            parts.field.pid = this.app.mongoose.Types.ObjectId(parts.field.pid); 
        } 

        let goodsCate = new this.ctx.model.GoodsCate(Object.assign(files, parts.field));

        await goodsCate.save();

        await this.success('/admin/goodsCate', '增加分类成功')
    }

    async edit() {
        let id = this.ctx.request.query.id;
        let result = await this.ctx.model.GoodsCate.find({"_id": id});      // 当前要编辑的数据

        let cateList = await this.ctx.model.GoodsCate.find({"pid": "0"});   // pid=0  表示顶级分类

        await this.ctx.render('admin/goodsCate/edit', {
            cateList: cateList,
            list: result[0]
        });
    }

    async doEdit() {
        // 获取上传的内容
        let parts = this.ctx.multipart({autoFields: true});
        let files = {};
        let stream;
        while ((stream = await parts()) != null ) {
            if (!stream.filename) {
                break;
            }
            let fieldname = stream.fieldname;   // file表单的名字

            let dir = await this.service.tools.getUploadFile(stream.filename);   // 返回上传路径地址与数据库保存地址
            let target = dir.uploadDir;
            let writeStream = fs.createWriteStream(target);

            await pump(stream, writeStream);  // 写入并销毁当前流  egg-demo方法

            files = Object.assign(files, {
                [fieldname]: dir.saveDir
            })

            // 上传图片成功以后  生成缩略图
            await this.service.tools.jimpImg(target);
        }

        // 如果分类 id 不等于 0  ，则不是顶级分类， 则需要将pid(字符串分类id) 转化为 ObjectId
        if (parts.field.pid != 0) {
            parts.field.pid = this.app.mongoose.Types.ObjectId(parts.field.pid); 
        } 

        let id = parts.field.id;

        let updateResult = Object.assign(files, parts.field);

        let result = await this.ctx.model.GoodsCate.updateOne({"_id": id}, updateResult);

        await this.success('/admin/goodsCate', '修改分类成功')
    }
}

module.exports = GoodsCateController;
